package com.lin.netty.module.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Scanner;

/**
 * ChannelFuture处理连接结果
 */
@Slf4j
public class ChannelFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(nioEventLoopGroup) // 1
                .channel(NioSocketChannel.class) // 2
                .handler(new ChannelInitializer<Channel>() { // 3
                    @Override
                    protected void initChannel(Channel ch) {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder()); // 8
                        ch.pipeline().addLast("i1", new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.debug("客户端收到消息：{}", msg);
                            }
                        });
                    }
                })
                // 异步非阻塞的 main线程调用了connect方法，就继续往下运行了，真正执行connect的是nio线程
                .connect("127.0.0.1", 1122);

        // 主线程阻塞等待nio线程连接完成
//        channelFuture.sync();
//        Channel channel = channelFuture.channel();
//        log.debug("{}", channel);
//        channel.writeAndFlush(" hello world!");

        // 异步等待nio线程连接完成，然后由nio线程来调用这个回调函数
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("连接成功：{}", channel);
//                channel.writeAndFlush("hello world!");

                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String line = scanner.nextLine();

                    if ("q".equals(line)) {
                        channel.close();
                        log.debug("关闭之后的操作");
                        nioEventLoopGroup.shutdownGracefully();
                        break;
                    }
                    channel.writeAndFlush(line);
                }
            }
        });


    }
}
